import { Button, Col, Form, Input, message, Modal, Row } from 'antd';
import React, { useState } from 'react';
import { useAntdTable } from 'ahooks';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';
import { GlobalFormLayout } from '@/layouts/Form';
import Space from '@/components/Space';

const columns = [
  {
    title: '用户ID',
    dataIndex: 'userId',
  },
  {
    title: '用户名',
    dataIndex: 'username',
  },
];

function fetchUsers({ current, pageSize, tenantId, username }) {
  return request.post('/tenant/pageUsersWithoutTenantId', {
    data: {
      current,
      pageSize,
      tenantId,
      username,
    },
  });
}
function AddUserModal({ tenantId, onCancel, onOk, form }) {
  const { getFieldsValue, getFieldDecorator, resetFields } = form;
  const { tableProps, refresh } = useAntdTable(
    query => fetchUsers({ ...query, tenantId, ...getFieldsValue() }),
    {
      defaultPageSize: 5,
    }
  );
  const [selectedRows, setSelectedRows] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleAddUser = () => {
    setLoading(true);
    request
      .post('/tenant/addUsers', {
        data: {
          tenantId,
          userIds: selectedRows.map(row => row.userId),
        },
      })
      .then(() => {
        message.success('添加成功');
        onOk();
      })
      .finally(() => setLoading(false));
  };

  return (
    <Modal
      title="添加用户"
      visible
      onOk={handleAddUser}
      onCancel={onCancel}
      okButtonProps={{ disabled: selectedRows.length === 0, loading }}
    >
      <Form className="margin-bottom" {...GlobalFormLayout}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label="用户名">
              {getFieldDecorator('username')(<Input onPressEnter={refresh} placeholder="请输入" />)}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Space>
              <Button type="primary" onClick={refresh}>
                查询
              </Button>
              <Button type="default" onClick={() => resetFields()}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <SlickTable
        pick="checkbox"
        onSelectRow={setSelectedRows}
        selectedRows={selectedRows}
        rowKey="userId"
        columns={columns}
        {...tableProps}
      />
    </Modal>
  );
}

export default Form.create()(AddUserModal);
